package com.risetechnology.krystalkitchen1;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Html;
import android.text.InputType;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.risetechnology.customviews.CustomFontEditText;
import com.risetechnology.data.Recipe;
import com.risetechnology.data.Schedule;
import com.risetechnology.utils.SmartSharedPreferrence;

public class ActivityViewSchedule extends Activity {

	private EditText tv_address;
	private TextView tv_starter, tv_main, tv_dessert;
	private String time = "", date = "";
	public static Schedule s;
	private String data = "";
	private View layoutInvitation;
	private String newData = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.activity_view_schedule);

		setContents();

		layoutInvitation = findViewById(R.id.layoutInvitation);
	}

	private void setContents() {
		// s = (Schedule) getIntent().getSerializableExtra("SCHEDULE");

		String dayOfMonth = s.getDayOfMonth();
		if (dayOfMonth.equalsIgnoreCase("1")
				|| dayOfMonth.equalsIgnoreCase("21")
				|| dayOfMonth.equalsIgnoreCase("31")) {
			dayOfMonth += "st";
		} else if (dayOfMonth.equalsIgnoreCase("2")
				|| dayOfMonth.equalsIgnoreCase("22")) {
			dayOfMonth += "nd";
		} else if (dayOfMonth.equalsIgnoreCase("3")
				|| dayOfMonth.equalsIgnoreCase("23")) {
			dayOfMonth += "rd";
		} else {
			dayOfMonth += "th";
		}
		String month = s.getMonth();
		String year = s.getYear();

		tv_address = (EditText) findViewById(R.id.tv_address);
		tv_address.clearFocus();
		tv_address.setText(SmartSharedPreferrence.getMailAddress(this, s.getId()));

		TextView textviewTime = (TextView) findViewById(R.id.tv_time);
		time = "Time: " + "<b>" + s.getSerTime() + "</b>";
		data += "Time: " + s.getSerTime();
		textviewTime.setText(Html.fromHtml(time));

		TextView textviewDate = (TextView) findViewById(R.id.tv_date);
		date = "Date: " + "<b>" + dayOfMonth + " " + month + ", " + year
				+ "</b>";
		data += ", " + dayOfMonth + " " + month + ", " + year;
		textviewDate.setText(Html.fromHtml(date));

		tv_starter = (TextView) findViewById(R.id.tv_starter);
		tv_main = (TextView) findViewById(R.id.tv_main);
		tv_dessert = (TextView) findViewById(R.id.tv_dessert);

		if (s.getEntree().trim().length() == 0) {
			findViewById(R.id.group_starter).setVisibility(View.GONE);
		} else {
			String temp = "";
			for (int i = 0; i < s.getEntreeRecipes().size() - 1; i++) {
				temp += s.getEntreeRecipes().get(i).getName() + ", ";
			}
			if (s.getEntreeRecipes().size() > 0) {
				temp += s.getEntreeRecipes()
						.get(s.getEntreeRecipes().size() - 1).getName();
			}
			tv_starter.setText(temp);
		}
		if (s.getMain().trim().length() == 0) {
			findViewById(R.id.group_main).setVisibility(View.GONE);
		} else {
			String temp = "";
			for (int i = 0; i < s.getMainRecipes().size() - 1; i++) {
				temp += s.getMainRecipes().get(i).getName() + ", ";
			}
			if (s.getMainRecipes().size() > 0) {
				temp += s.getMainRecipes().get(s.getMainRecipes().size() - 1)
						.getName();
			}
			tv_main.setText(temp);
		}

		if (s.getDessert().trim().length() == 0) {
			findViewById(R.id.group_dessert).setVisibility(View.GONE);
		} else {

			String temp = "";
			for (int i = 0; i < s.getDessertRecipes().size() - 1; i++) {
				temp += s.getDessertRecipes().get(i).getName() + ", ";
			}
			if (s.getDessertRecipes().size() > 0) {
				temp += s.getDessertRecipes()
						.get(s.getDessertRecipes().size() - 1).getName();
			}
			tv_dessert.setText(temp);
		}
	}

	public void onOption(View v) {
		if (tv_address.getText().toString().trim().length() == 0) {
			Toast.makeText(ActivityViewSchedule.this, "Please input address",
					Toast.LENGTH_SHORT).show();
			return;
		}
		
		if (!TabsManager.loadMailOk) {
			Toast.makeText(ActivityViewSchedule.this, "Getting mail contact...\nTry again in a few secs.",
					Toast.LENGTH_SHORT).show();
			return;
		}
		
		showOptionsDialog();
	}

	public static Bitmap getBitmapFromView(View view) {

		// Define a bitmap with the same size as the view
		Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(),
				view.getHeight(), Bitmap.Config.ARGB_8888);
		// Bind a canvas to it
		Canvas canvas = new Canvas(returnedBitmap);
		// Get the view's background
		Drawable bgDrawable = view.getBackground();
		if (bgDrawable != null)
			// has background drawable, then draw it on the canvas
			bgDrawable.draw(canvas);
		else
			// does not have background drawable, then draw white background on
			// the canvas
			canvas.drawColor(Color.WHITE);
		// draw the view on the canvas
		view.draw(canvas);
		// return the bitmap
		return returnedBitmap;
	}
	
	@SuppressWarnings("deprecation")
	private void showOptionsDialog() {
		newData = "<b>You're invited to Dine with me!</b><br/><br/>";
		newData += time + "<br/>" + date + "<br/>";

		newData += "At: <b>" + tv_address.getText().toString().trim()
				+ "</b><br/>";

		String start = tv_starter.getText().toString();
		if (start.length() > 0) {
			newData += "Starter: <b>" + start + "</b><br/>";
		}

		String main = tv_main.getText().toString();
		if (main.length() > 0) {
			newData += "Main Meal & Sides: <b>" + main + "</b><br/>";
		}

		String dessert = tv_dessert.getText().toString();
		if (dessert.length() > 0) {
			newData += "Dessert: <b>" + dessert + "</b><br/><br/>";
		}

		newData += "<b>You have been invited to this event.</b>";
		
		
		final Dialog dialog = new Dialog(ActivityViewSchedule.this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_send_email_options);

		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();

		wlp.gravity = Gravity.CENTER;
		wlp.width = WindowManager.LayoutParams.FILL_PARENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);

		dialog.getWindow().setAttributes(wlp);

		LinearLayout cameraLayout = (LinearLayout) dialog
				.findViewById(R.id.layout_camera);
		cameraLayout.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
				showInputEmailDialog(0);
			}
		});

		LinearLayout galleryLayout = (LinearLayout) dialog
				.findViewById(R.id.layout_gallery);
		galleryLayout.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
				showInputEmailDialog(1);
			}
		});

		dialog.show();
	}
	
	private void showInputEmailDialog(int type) {
		if(type != 0){ // Select from exist
			new ChooseEmailDialog(this,
				TabsManager.mails, 
				new ChooseEmailDialog.SelectedListener() {

					@Override
					public void onSelected(ArrayList<String> choosenRecipe) {
						String email = "";
						if(choosenRecipe.size()>0){
							email = choosenRecipe.get(0);
						}
						for (int i = 1; i < choosenRecipe.size(); i++) {
							email += "," + choosenRecipe.get(i);
						}
						
						new CreateImage().execute(newData, email);
					}
				}).show();
			
		}else{
			final Dialog dialog = new Dialog(this);
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(R.layout.dialog_input_part_name);
	
			Window window = dialog.getWindow();
			WindowManager.LayoutParams wlp = window.getAttributes();
	
			wlp.gravity = Gravity.CENTER;
			wlp.width = WindowManager.LayoutParams.FILL_PARENT;
			wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
			window.setAttributes(wlp);
	
			dialog.getWindow().setAttributes(wlp);
	
			dialog.show();
	
			TextView tv = (TextView) dialog.findViewById(R.id.tv_title);
			tv.setText("Input Email Address");
	
			final EditText edt_email = (EditText) dialog
					.findViewById(R.id.et_part_name);
			edt_email.setHint("Input Email Address");
			edt_email.setInputType(InputType.TYPE_CLASS_TEXT
					| InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
	
			// edt_email.setText("ninhngoc.t4.bkdn@gmail.com");
	
			Button buttonOK = (Button) dialog.findViewById(R.id.btn_ok);
			buttonOK.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					String email = edt_email.getText().toString();
					if (email.trim().length() == 0) {
						Toast.makeText(ActivityViewSchedule.this,
								"Please input email", Toast.LENGTH_SHORT).show();
						return;
					}
					if (!isEmailValid(email)) {
						Toast.makeText(ActivityViewSchedule.this,
								"Please input correct email!", Toast.LENGTH_SHORT)
								.show();
						return;
					}
	
					
	
					new CreateImage().execute(newData, email);
	
					dialog.dismiss();
				}
			});
		
		}
	}

	private class CreateImage extends AsyncTask<String, Void, String> {
		private ProgressDialog pd;
		private String email = "", text = "";

		@Override
		protected void onPreExecute() {
			pd = new ProgressDialog(ActivityViewSchedule.this);
			pd.setCancelable(false);
			pd.setMessage("Creating invitation...");
			pd.show();

			tv_address.setBackgroundDrawable(null);
		}

		@Override
		protected String doInBackground(String... arg0) {
			text = arg0[0];
			if (arg0.length >= 2) {
				email = arg0[1];
			} else {
				email = null;
			}
			try {
				File file = getExternalFilesDir("DIRECTORY_PICTURES");
				File f = new File(file.getPath() + "/image_ivitation.jpg");
				if (f.exists()) {
					f.delete();
				}
				f.createNewFile();

				Bitmap bmp = getBitmapFromView(layoutInvitation);
				bmp.compress(CompressFormat.JPEG, 100, new FileOutputStream(f));

				return f.getPath();
			} catch (Exception e) {
			}
			return "";
		}

		@Override
		protected void onPostExecute(String result) {
			pd.dismiss();

			if (result.length() > 0) {
				if (email != null) {
					Intent emailIntent = new Intent(Intent.ACTION_SENDTO,
							Uri.fromParts("mailto", email, null));
					emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Invitation");
					emailIntent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(text));
					emailIntent.putExtra(Intent.EXTRA_STREAM,
							Uri.fromFile(new File(result)));
					startActivity(emailIntent);
				}
				//else{
				// Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
				// emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Invitation");
				// emailIntent
				// .putExtra(Intent.EXTRA_TEXT, Html.fromHtml(text));
				// emailIntent.putExtra(Intent.EXTRA_STREAM,
				// Uri.fromFile(new File(result)));
				// startActivity(Intent.createChooser(emailIntent,
				// "Send mail..."));
				// }
			}

			finish();
		}
	}

	boolean isEmailValid(CharSequence email) {
		return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
	}

	@Override
	public boolean dispatchTouchEvent(final MotionEvent ev) {
		// all touch events close the keyboard before they are processed except
		// EditText instances.
		// if focus is an EditText we need to check, if the touchevent was
		// inside the focus editTexts
		final View currentFocus = getCurrentFocus();

		if (!(currentFocus instanceof EditText)
				|| !isTouchInsideView(ev, currentFocus)) {
			((InputMethodManager) getApplicationContext().getSystemService(
					Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
					getCurrentFocus().getWindowToken(),
					InputMethodManager.HIDE_NOT_ALWAYS);
			if (currentFocus instanceof EditText) {
				EditText edt = (EditText) currentFocus;
				edt.setCursorVisible(false);
			}
		}
		return super.dispatchTouchEvent(ev);
	}

	/**
	 * determine if the given motionevent is inside the given view.
	 * 
	 * @param ev
	 *            the given view
	 * @param currentFocus
	 *            the motion event.
	 * @return if the given motionevent is inside the given view
	 */
	private boolean isTouchInsideView(final MotionEvent ev,
			final View currentFocus) {
		if (currentFocus instanceof EditText) {
			EditText edt = (EditText) currentFocus;
			edt.setCursorVisible(true);
		}
		final int[] loc = new int[2];
		currentFocus.getLocationOnScreen(loc);
		return ev.getRawX() > loc[0] && ev.getRawY() > loc[1]
				&& ev.getRawX() < (loc[0] + currentFocus.getWidth())
				&& ev.getRawY() < (loc[1] + currentFocus.getHeight());
	}

	@Override
	protected void onStop() {
		SmartSharedPreferrence.setMailAddress(this, s.getId(), tv_address.getText()
				.toString().trim());
		super.onStop();
	}
}
